package net.pws.oos.biz.query.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.pws.common.beanutils.BeanUtils;
import net.pws.common.persistence.IPage;
import net.pws.oos.biz.model.Dict;
import net.pws.oos.biz.model.IndicatorTemplate;
import net.pws.oos.biz.model.IndicatorValue;
import net.pws.oos.biz.model.User;
import net.pws.oos.biz.query.IndicatorTemplateFinder;
import net.pws.oos.biz.query.parameter.IndicatorTemplateQueryParameter;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings({ "rawtypes", "unchecked" })
public class DefaultIndicatorTemplateFinder extends AbstractFinder implements IndicatorTemplateFinder {
	
    public int countIndicatorTemplate(IndicatorTemplateQueryParameter queryParameter) {
        if (StringUtils.isNotEmpty(queryParameter.getName())) {
            return ((Number) entityManager.findUnique("select count(o.id) from IndicatorTemplate o where o.deleted = false and o.name like ?",
                                                      new Object[] { "%" + queryParameter.getName() + "%"})).intValue();
        }
        
        return ((Number) entityManager.findUnique("select count(o.id) from IndicatorTemplate o where o.deleted = false ",
                                                  new HashMap())).intValue();
    }
    
    
    public List<Map> getIndicatorTemplateMapList(IndicatorTemplateQueryParameter queryParameter,
                                            int start,
                                            int limit) {
    	StringBuffer conditonhql = new StringBuffer();
    	List params = new ArrayList();
    	
    	if(StringUtils.isNotEmpty(queryParameter.getName())){
    		conditonhql.append(" and o.name like ? ");
    		params.add("%" + queryParameter.getName() + "%");
    	}
    	if(StringUtils.isNotEmpty(queryParameter.getSpecialId())){
    		conditonhql.append(" and sp.id = ? ");
    		params.add( queryParameter.getSpecialId());
    	}

		return (List<Map>) ((IPage) entityManager.findPage(
						String.format("select count(o.id) from IndicatorTemplate o left join o.special sp where o.deleted = false %s ", conditonhql.toString()),
						String.format("select new map(o.id as id,o.name as name,o.createDateTime as createDateTime,sp.name as specialName,c.name as creatorName) from IndicatorTemplate o left join o.special sp left join o.creator c where o.deleted = false %s order by o.createDateTime desc,o.name", conditonhql.toString()), params.toArray(),
						start, limit)).getData();
    }
    
    
    public IndicatorTemplate getIndicatorTemplate(String id) {
        return (IndicatorTemplate) entityManager.findFirst("select o from IndicatorTemplate o left join o.parent where o.deleted = false and o.id = ?",
                                                      new Object[] { id });
    }
    
    public IndicatorTemplate getIndicatorTemplateMap(String id) {
        IndicatorTemplate indicatorTemplate = null;
        Map map = (Map) entityManager.findFirst("select new map(o.id as id,o.name as name,sp.id as specialId,o.description as description,o.deleted as deleted,o.createDateTime as createDateTime,o.deleteDateTime as deleteDateTime,c.id as creatorId,cm.id as constructionModelId, cm.name as constructionModelName ) from IndicatorTemplate o left join o.special sp left join o.creator c left join o.constructionModel cm where o.deleted = false and o.id = ?",
                                                new Object[] { id });
        if (map != null) {
            indicatorTemplate = new IndicatorTemplate();
            BeanUtils.copyProperties(indicatorTemplate, map);
            String specialId = (String) map.get("specialId");
            if (StringUtils.isNotEmpty(specialId)) {
            	Dict special = entityManager.find(Dict.class, specialId);
                indicatorTemplate.setSpecial(special);
            }
            String constructionModelId = (String) map.get("constructionModelId");
            if (StringUtils.isNotEmpty(constructionModelId)) {
            	IndicatorValue constructionModel = entityManager.find(IndicatorValue.class, constructionModelId);
                indicatorTemplate.setConstructionModel(constructionModel);
            }
            String creatorId = (String) map.get("creatorId");
            if (StringUtils.isNotEmpty(creatorId)) {
            	User creator = entityManager.find(User.class, creatorId);
                indicatorTemplate.setCreator(creator);
            }

        }
        
        return indicatorTemplate;
    }


	@Override
	public List<Map> getIndicatorTemplateTreeNode(String id, String templateId) {

        if (StringUtils.isEmpty(id)) {
            return (List<Map>) entityManager.findList("select new map(o.id as id,o.name as name,o.shortName as shortName,o.depth as depth,(select d.id from IndicatorTemplateDetail d where d.template.id=? and d.indicator.id=o.id) as detailId) from Indicator o where o.deleted = false and o.depth = 0 order by o.sortNum",
                                                               new Object[] { templateId });
        }
        return (List<Map>) entityManager.findList("select new map(o.id as id,o.name as name,o.shortName as shortName,o.depth as depth,(select d.id from IndicatorTemplateDetail d where d.template.id=? and d.indicator.id=o.id) as detailId) from Indicator o where o.deleted = false and o.parent.id = ? and o.depth < 4 and o.name<>'基础信息' order by o.depth,o.sortNum",
                                                           new Object[] { templateId, id });
	}
}
